package com.zh.kotlin_mvvm.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.text.TextPaint
import android.text.TextUtils
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.zh.common.ktx.dp2px
import com.zh.kotlin_mvvm.R

class StickyDecoration(context: Context, private val callback: DecorationCallback) :
    RecyclerView.ItemDecoration() {
    private val textPaint: TextPaint
    private val paint: Paint = Paint()
    private val topHead: Int

    init {
        paint.color = ContextCompat.getColor(context, R.color.color_line)
        textPaint = TextPaint()
        //textPaint.typeface = Typeface.DEFAULT_BOLD;
        textPaint.isFakeBoldText = false
        textPaint.isAntiAlias = true
        textPaint.textSize = 14f.dp2px.toFloat()
        textPaint.color = Color.parseColor("#333333")
        textPaint.textAlign = Paint.Align.LEFT
        topHead = 30f.dp2px
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        val pos = parent.getChildAdapterPosition(view)
        val data = callback.getData(pos)
        if (TextUtils.isEmpty(data)) {
            return
        }
        //同组的第一个才添加padding
        if (pos == 0 || isHeader(pos)) {
            outRect.top = topHead
        } else {
            outRect.top = 0
        }
    }

    override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDrawOver(c, parent, state)
        //获取当前可见的item的数量，不包括分组项，注意区分下面的
        val childCount = parent.childCount
        //获取所有的的item个数,不建议使用Adapter中获取
        val itemCount = state.itemCount
        val left = parent.left + parent.paddingLeft
        val right = parent.right - parent.paddingRight
        var preDate: String?
        var currentDate: String? = null
        for (i in 0 until childCount) {
            val view = parent.getChildAt(i)
            val position = parent.getChildAdapterPosition(view)
            val textLine = callback.getData(position)
            preDate = currentDate
            currentDate = callback.getData(position)
            if (TextUtils.isEmpty(currentDate) || TextUtils.equals(currentDate, preDate)) {
                continue
            }
            if (TextUtils.isEmpty(textLine)) {
                continue
            }
            val viewBottom = view.bottom
            var textY = Math.max(topHead, view.top).toFloat()
            //下一个和当前不一样移动当前
            if (position + 1 < itemCount) {
                val nextData = callback.getData(position + 1)
                if (currentDate != nextData && viewBottom < textY) { //组内最后一个view进入了header
                    textY = viewBottom.toFloat()
                }
            }
            val rect = Rect(left, textY.toInt() - topHead, right, textY.toInt())
            c.drawRect(rect, paint)
            //绘制文字基线，文字的的绘制是从绘制的矩形底部开始的
            val fontMetrics: Paint.FontMetrics = textPaint.fontMetrics
            val baseline = (rect.bottom + rect.top - fontMetrics.bottom - fontMetrics.top) / 2
            textPaint.textAlign = Paint.Align.CENTER //文字居中
            //绘制文本
            c.drawText(textLine, topHead.toFloat(), baseline, textPaint)
        }
    }

    private fun isHeader(pos: Int): Boolean {
        return if (pos == 0) {
            true
        } else {
            val preData = callback.getData(pos - 1)
            val data = callback.getData(pos)
            preData != data
        }
    }

    interface DecorationCallback {
        fun getData(position: Int): String
    }
}